﻿using System.Windows.Controls;
using Microsoft.Maps.MapControl;
using System;
using iTraffic.GeocodeServiceReference;
using iTraffic.UserControls;

namespace iTraffic
{
    public partial class MainPage : UserControl
    {
        GeocodeServicesSoapClient _geocodeServiceclient;

        public MainPage()
        {
            InitializeComponent();
            _geocodeServiceclient = new GeocodeServiceReference.GeocodeServicesSoapClient();
            _geocodeServiceclient.GeocodeServiceCompleted += new EventHandler<GeocodeServiceCompletedEventArgs>(_geocodeServiceclient_GeocodeServiceCompleted);
            
            MyMap.MouseDoubleClick += new EventHandler<MapMouseEventArgs>(MyMap_MouseClick);            
        }
        

        void MyMap_MouseClick(object sender, MapMouseEventArgs e)
        {
            e.Handled = true;
            Location location = MyMap.ViewportPointToLocation(e.ViewportPoint);
            _geocodeServiceclient.GeocodeServiceAsync(location.Latitude + "," + location.Longitude);            
        }

        void _geocodeServiceclient_GeocodeServiceCompleted(object sender, GeocodeServiceCompletedEventArgs e)
        {
            SerializedAddress adress = e.Result;
            DraggablePushpin pin = new DraggablePushpin();
            pin.Location = new Location(adress.Coordinates.Latitude, adress.Coordinates.Longitude);
            pin.PinAddress = adress;
            pin.MouseEnter += new System.Windows.Input.MouseEventHandler(pin_MouseEnter);
            pin.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(pin_MouseLeftButtonDown);
            PushpinLayer.Children.Add(pin);
        }

        void pin_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            SerializedAddress address = (sender as DraggablePushpin).PinAddress;
            TbAccuracy.Text = address.Accuracy;
            TbCity.Text = address.City;
            TbConfidence.Text = address.Confidence;
            TbCountry.Text = address.Country;
            TbLatitude.Text = address.Coordinates.Latitude.ToString();
            TbLongitude.Text = address.Coordinates.Longitude.ToString();
            TbPostalCode.Text = address.PostalCode;
            TbState.Text = address.State;
            TbStreet.Text = address.Street;
        }

        void pin_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            MyMap.Center = (sender as DraggablePushpin).Location;            
            PicturesViewer picviewer = new PicturesViewer();
            picviewer.Show();
        }
    }
}
